package ua.keeper.query;

import java.util.ArrayList;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

public class ClientList
{
    private SQLiteDatabase db_;
    private int dayOfWeek_ = 0;
    /*****************************************************************************************/
    
    public ArrayList<ClientListItem> list = new ArrayList<ClientListItem>();
    /*****************************************************************************************/
    
    ClientList(SQLiteDatabase dataBase, int dayOfWeek)
    {
    	dayOfWeek_ = dayOfWeek;
    	Log.i("ClientList", "Constructor");
    	db_ = dataBase;
    	if (!db_.isOpen())
    	{
    		Log.w("ClientList.Init()", "DataBase is not opened!");
    		return;
    	}
    	fillList();
    }
    
    /*****************************************************************************************/
    private void fillList()
    {
    	Cursor cursor = db_.rawQuery("SELECT clients.id_, clients.title, code, SUM(q * price)" +
			" FROM clients" +
			" LEFT OUTER JOIN query_h ON query_h.client = clients.id_" +
			" LEFT OUTER JOIN query_d ON query_d.head = query_h.id_" +
			" LEFT OUTER JOIN goods ON query_d.goods = goods.id_" +
			" WHERE day = ?" +
			" GROUP BY  client, clients.title, code" +
			" ORDER BY clients.id_", new String[] { Integer.toString(dayOfWeek_) });

    	int queryCount = cursor.getCount();
    	if (queryCount == 0)
    	{
    		Log.w("ClientList.getList()", "Cursor is empty!");
    	}
    	
    	cursor.moveToFirst();
    	while(!cursor.isAfterLast())
        {
    		int client_id = cursor.getInt(0);
    		// select count of doc_heads by client
    		Cursor cursor_count = db_.rawQuery("SELECT COUNT(query_h.id_) FROM query_h WHERE client = ?",
    				 new String[] { Integer.toString(client_id) });
    		cursor_count.moveToFirst();
    		
    		ClientListItem item = new ClientListItem(client_id, cursor.getString(1), cursor.getString(2),
    				cursor_count.getInt(0), cursor.getDouble(3));
    		list.add(item);
    		cursor.moveToNext();
    		cursor_count.close();
        }
        cursor.close();
    }
    /*****************************************************************************************/
}

